package topuc.com.mvp;

import android.Manifest;
import android.graphics.BitmapFactory;
import android.graphics.Camera;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapOptions;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.navi.enums.PathPlanningStrategy;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeAddress;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DistanceItem;
import com.amap.api.services.route.DistanceResult;
import com.amap.api.services.route.DistanceSearch;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkRouteResult;

import java.util.ArrayList;
import java.util.List;

import pub.devrel.easypermissions.EasyPermissions;

public class ShowPositionActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks, LocationSource {

    private MapView mapView;
    private AMap aMap;
    private TextView tvStart;
    private static final int RC_LOCATION = 1;
    private TextView tvDriverTime;
    private TextView tvBusTime;
    private TextView tvFootTime;

    private RelativeLayout rlDriver;
    private RelativeLayout rlBus;
    private RelativeLayout rlFoot;

    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;

    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;

    private String[] permissionPerms = {Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION};
    private LatLng centerSHpoint = new LatLng(31.238068, 121.501654);// 上海市经纬度

    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {

            Log.d("MainActivity", "city:" + aMapLocation.getCity());
            Log.d("MainActivity", "address:" + aMapLocation.getAddress());
            Log.d("MainActivity", "纬度:" + aMapLocation.getLatitude());
            Log.d("MainActivity", "经度:" + aMapLocation.getLongitude());

            LatLonPoint latLonPoint=new LatLonPoint(aMapLocation.getLatitude(),aMapLocation.getLongitude());

            getDistance("上海虹口区海伦路地铁站1号口",latLonPoint);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_position);

        initView(savedInstanceState);
    }

    private void initView(Bundle savedInstanceState) {

        tvDriverTime=findViewById(R.id.tv_driver_time);
        tvBusTime=findViewById(R.id.tv_bus_time);
        tvFootTime=findViewById(R.id.tv_foot_time);

        rlBus=findViewById(R.id.rl_bus);
        rlFoot=findViewById(R.id.rl_foot);
        rlDriver=findViewById(R.id.rl_driver);

        rlBus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                RouteSearch routeSearch = new RouteSearch(ShowPositionActivity.this);

                //模拟起始点与目的经纬度（如：深圳市）
                RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(new LatLonPoint(22.5587, 113.8727), new LatLonPoint(22.5587, 113.8950));
                RouteSearch.DriveRouteQuery query = new RouteSearch.DriveRouteQuery(fromAndTo, PathPlanningStrategy.DRIVING_DEFAULT, null, null, "");
                routeSearch.calculateDriveRouteAsyn(query);
                routeSearch.setRouteSearchListener(new RouteSearch.OnRouteSearchListener() {
                    @Override
                    public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {

                    }

                    @Override
                    public void onDriveRouteSearched(DriveRouteResult driveRouteResult, int i) {

                        DrivePath drivePath = driveRouteResult.getPaths().get(0);
//                        setDrivingRoute(drivePath, driveRouteResult.getStartPos(), driveRouteResult.getTargetPos());
                        //策略
                        String strategy = drivePath.getStrategy();
                        //总的交通信号灯数
                        int clights = drivePath.getTotalTrafficlights();
                        //距离 米：/1000转公里 1公里=1km
                        float distance = drivePath.getDistance() / 1000;
                        //时间 秒：、60转分
                        long duration = drivePath.getDuration() / 60;
                        tvDriverTime.setText("策略：" + strategy + "\n总的交通信号灯数/个："+ clights +"\n距离/公里："+ distance + "\n时间/分：" + duration);
                    }

                    @Override
                    public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {

                    }

                    @Override
                    public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {

                    }
                });

            }
        });

        rlFoot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        rlDriver.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        mapView=findViewById(R.id.mapview);
        mapView.onCreate(savedInstanceState);

        tvStart=findViewById(R.id.tv_start);
        aMap=mapView.getMap();
        //使用默认标记
//        Marker marker=aMap.addMarker(new MarkerOptions().position(new LatLng(1,1)).title("地点").snippet("呵呵"));

        tvStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                checkLocation();
            }
        });


    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

        if (EasyPermissions.hasPermissions(ShowPositionActivity.this, permissionPerms)) {

            initLocation();

        } else {

            Toast.makeText(ShowPositionActivity.this, "您已经拒绝了我们所需(内部存储)权限，请到'系统设置'中打开这个权限", Toast.LENGTH_LONG).show();
            Log.d("OnLineResumeActivity1", "onPermissionsGranted:拒绝了权限");

        }

    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {

        Toast.makeText(ShowPositionActivity.this, "您已经拒绝了我们所需(内部存储)权限，请到'系统设置'中打开这个权限", Toast.LENGTH_LONG).show();
    }

    /**
     * 当用户点击拍照上传头像时，调用，检查相机权限
     */
    private void checkLocation() {

        if (EasyPermissions.hasPermissions(this, permissionPerms)) {

            //初始化定位信息
            initLocation();
        } else {

            EasyPermissions.requestPermissions(this, "您必须授权开启(内部存储和相机)权限，才能进行下一步操作", RC_LOCATION, permissionPerms);
        }

    }

    private void initLocation() {

        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);

        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);

        /**
         * 设置定位场景，目前支持三种场景（签到、出行、运动，默认无场景）
         */
        mLocationOption.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn);
        if (null != mLocationClient) {
            mLocationClient.setLocationOption(mLocationOption);
            //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
            mLocationClient.stopLocation();
            mLocationClient.startLocation();
        }
    }

    /**
     * 根据位置的名称获取，到定位位置的距离
     *
     * @param locationName 起点位置的名称
     * @param latLonPoint  目的地的经纬度坐标
     */
    private void getDistance(final String locationName,LatLonPoint latLonPoint) {

        List<LatLonPoint> mList=new ArrayList<>();
        mList.add(latLonPoint);

        GeocodeSearch geocodeSearch = new GeocodeSearch(this);
        GeocodeQuery geocodeQuery = new GeocodeQuery(locationName, "上海");
        geocodeSearch.getFromLocationNameAsyn(geocodeQuery);

        final DistanceSearch.DistanceQuery distanceQuery=new DistanceSearch.DistanceQuery();
        distanceQuery.setOrigins(mList);

        geocodeSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
            @Override
            public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {

            }

            @Override
            public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

                List<GeocodeAddress> mList = geocodeResult.getGeocodeAddressList();
                LatLonPoint latLonPoint = mList.get(0).getLatLonPoint();

                AMapOptions aOptions = new AMapOptions();
                aOptions.camera(new CameraPosition(centerSHpoint, 10f, 0, 0));

                LatLng point =new LatLng(31.2993790000,120.6195830000); //苏州市中心点坐标（注意是高德坐标）
                CameraPosition LUJIAZUI = new CameraPosition.Builder().target(point).zoom(17).build();
                aOptions.camera(LUJIAZUI);

                //设置地图的放缩级别和地图应该显示的经纬度
                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latLonPoint.getLatitude(),latLonPoint.getLongitude()),12));
                //绘制标记点
                final Marker marker = aMap.addMarker(new MarkerOptions().position(new LatLng(latLonPoint.getLatitude(),latLonPoint.getLongitude())).title(locationName).snippet("DefaultMarker"));


                distanceQuery.setDestination(latLonPoint);
                distanceQuery.setType(DistanceSearch.TYPE_DRIVING_DISTANCE);

                DistanceSearch distanceSearch=new DistanceSearch(ShowPositionActivity.this);
                distanceSearch.calculateRouteDistanceAsyn(distanceQuery);

                distanceSearch.setDistanceSearchListener(new DistanceSearch.OnDistanceSearchListener() {
                    @Override
                    public void onDistanceSearched(DistanceResult distanceResult, int i) {

                        List<DistanceItem> mList=distanceResult.getDistanceResults();
                        float distance=mList.get(0).getDistance();

                        Log.d("MainActivity","distance:"+distance);
                    }
                });
            }
        });

    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {

    }

    @Override
    public void deactivate() {

    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }


}
